package clinic.ms.service;

import clinic.ms.entity.Item;
import clinic.ms.mapper.ItemMapper;
import clinic.ms.entity.Pie;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


@Service
public class ItemService {
    @Autowired
    ItemMapper itemMapper;

    // 根据编号查询，返回一个
    public Item queryByNo(String itemNo){
        //System.out.println(itemNo);
        return itemMapper.queryByNo(itemNo);
    }

    // 根据名称查询
    /*
    public Item queryByName(String itemName){
        //System.out.println(itemName);
        return itemMapper.queryByName(itemName);
    }
     */

    // 模糊查询，根据编号和名称，返回List
    public ArrayList<Item> queryByNameAndNo(String itemNo, String itemName) {
        return itemMapper.queryByNameAndNo(itemNo,itemName);
    }

    public String insertItem(Item item){
        // 根据日期生成药品编号
        Date date = new Date();
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
        String formatDate = format.format(date);
        System.out.println(formatDate);
        item.setItemNo(formatDate);
        System.out.println(item.getItemIdCard());
        if(itemMapper.insert(item) != 1){ // 插入失败会报错,但好像不会插入失败，除非同时插入两个
            return null;
        }
        else return formatDate;
    }

    public boolean delete(String itemNo) throws Exception{
        // 插入成功返回1，删除不存在的返回0，否则报错
        return itemMapper.deleteByNo(itemNo) == 1;
    }

    public void updateNumsByNo(String itemNo, int num){
        int result = itemMapper.updateNumsByNo(itemNo,num);
        if(result == 1){
            itemMapper.queryByNo(itemNo);
        }

    }


    public boolean updateByNo(Item item) {
        return itemMapper.updateByNo(item) == 1;
    }

    public List<Pie> statisticsType(){
        List<Pie> pieList = new ArrayList<>();
        List<String> typeList = new ArrayList<>();
        typeList = itemMapper.queryTypes();
        int i = 0,total,num;
        total = itemMapper.getAllNums();
        String name;
        System.out.println(total);
        while(i<typeList.size()) {
            name = typeList.get(i++);
            num = itemMapper.sumByType(name);
            pieList.add(new Pie(name,num,0));

        }
        return pieList;
    }
}
